package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.FireTaskActivity;
import com.mingtu.jgspatrol.activity.ReportedDetailsActivity;
import com.mingtu.jgspatrol.activity.TaskDetails2Activity;
import com.mingtu.jgspatrol.adapter.ReceiveUndoTaskAdapter;
import com.mingtu.jgspatrol.bean.TaskListCommonBean;
import com.mingtu.jgspatrol.databinding.FragmentReceiveUndoTaskBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReceiveUndoTaskFragment extends BaseBindingFragment<FragmentReceiveUndoTaskBinding> implements LazyFragmentPagerAdapter.Laziable {
    
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private ReceiveUndoTaskAdapter receiveUndoTaskAdapter;
    private List<TaskListCommonBean.PageBean.ListBean> DataBean = new ArrayList<>();

    public static ReceiveUndoTaskFragment getInstance() {
        ReceiveUndoTaskFragment fragment = new ReceiveUndoTaskFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_receive_undo_task;
    }


    @Override
    protected void initData() {
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        receiveUndoTaskAdapter = new ReceiveUndoTaskAdapter(DataBean);
        if (isOpenLoadAnimation) {
            receiveUndoTaskAdapter.isFirstOnly(isFirstOnly);
            receiveUndoTaskAdapter.openLoadAnimation(animationType);
        }

        receiveUndoTaskAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(receiveUndoTaskAdapter);
        receiveUndoTaskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TaskListCommonBean.PageBean.ListBean listBean = receiveUndoTaskAdapter.getData().get(position);
                int taskType = listBean.getType();
                int taskId = listBean.getId();
                switch (taskType) { //1：巡护任务 2：下发、临时任务 3：上报事件 4:火情任务
                    case 1:
                        ToastUtils.showLong("巡护任务没有详情哦~");
                        break;
                    case 2://临时任务详情
                        Intent intent2 = new Intent(getActivity(), TaskDetails2Activity.class);
                        intent2.putExtra("taskId", taskId + "");
                        intent2.putExtra("taskType", MyConstant.TASK_TYPE_SEND);
                        startActivityForResult(intent2, 100);
                        break;
                    case 3://上报任务详情
                        Intent intent3 = new Intent(getActivity(), ReportedDetailsActivity.class);
                        intent3.putExtra("eventId", taskId + "");
                        intent3.putExtra("sourceType", "0");
                        startActivityForResult(intent3, 100);
                        break;
                    case 4: //火情任务详情
                        Bundle bundle4 = new Bundle();
                        bundle4.putString("taskId", taskId + "");
                        bundle4.putString("taskType", MyConstant.TASK_TYPE_FIRE);
                        IntentUtils.getInstance().readyGo(getActivity(), FireTaskActivity.class, bundle4);
                        break;
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getUndoTaskList(1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == 200) {
//                getUndoTaskList(1);

                ((ReceiveTaskFragment) (ReceiveUndoTaskFragment.this.getParentFragment())).refreshReceiveUndoTaskData();
                ((ReceiveTaskFragment) (ReceiveUndoTaskFragment.this.getParentFragment())).refreshFinishTaskData();

            }
        }
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getUndoTaskList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(receiveUndoTaskAdapter.getData(), Constant.PAGE_SIZE);
                    getUndoTaskList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    /**
     * 我接收的-待完成的任务列表
     */
    public void getUndoTaskList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_TASK)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                TaskListCommonBean taskListCommonBean = new TaskListCommonBean();
                                taskListCommonBean = gson.fromJson(result, TaskListCommonBean.class);
                                List<TaskListCommonBean.PageBean.ListBean> dataBeans = taskListCommonBean.getPage().getList();

                                try {

                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            receiveUndoTaskAdapter.replaceData(dataBeans);
                                        } else {
                                            receiveUndoTaskAdapter.addData(dataBeans);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });

    }

    public void refresh() {
        getUndoTaskList(1);
    }


}